<?PHP
/*
*	File: 		includes/users/users.class.php
*	Use:		Users Class
*	Functions:	newsession($db)
*				updatesession($db)
*				login($db, $username, $password)
*				logout($db)
*				auth($db, $type)
*				reg($db, $username, $rname, $pword)
*
*	Misc:		Class: users
*				Description: handles querys about users (logins, profile changes, etc)
*
*	Coder:		Andrew Thorne, UK
*	Copyright:	No part of this code may be used for any purpose other 
*				than the original intended purpose without prior written 
*				permission of Andrew Thorne. 
*				Use for any other purpose is expressly prohibited by law, 
*				and may result in civil and criminal penalties.
*
*	Contact:	omgrofl@hotmail.co.uk
*
*/
	

class users {

	
	/* 
	*
	* Function: newsession
	* Args: 	$db	- The database object
	* Descript:	When we have a new user, make a new session 
	*			In here we want the user's IP and user agent
	* Returns:	nothing
	*
	*/
	public function newsession($db){
		
		$prefix = $db->getPrefix();	
		session_start(); 
		$db->query("INSERT INTO ".$prefix."sessions VALUES('". session_id() . "', '" . $_SERVER['REMOTE_ADDR'] . "', '" . $_SERVER['HTTP_USER_AGENT'] . "', '" . $_SERVER["REQUEST_URI"] . "', 0, " . time() . ")");
		$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT']; 
		$_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; 
		$_SESSION["sessionid"] = session_id();
		$_SESSION["logged_in"] = false;
		$_SESSION["uid"] = 0;
		$_SESSION["groupid"] = 0;
		
	}
	

	/* 
	*
	* Function: updatesession
	* Args: 	$db	- The database object
	* Descript:	When we a user changes page 
	*			In here we want the user's IP and user agent
	* Returns:	[string] if hijack, else nothing.
	*
	*/
	public function updatesession($db){
		
		$prefix = $db->getPrefix();	
		session_start(); 
		if ($_SESSION['user_agent'] == $_SERVER['HTTP_USER_AGENT']){ 
			$db->query("UPDATE ".$prefix."sessions SET location='" . $db->prep($_SERVER['REQUEST_URI']) . "', activitytime=" . time() . " WHERE sessionid='". session_id() . "'");
		} else {
			echo "Session hijack detected. Your IP address has been logged";
			session_destroy();
		}
		
		//clean up
		$cutoff = time()-600;
		$outcome = $db->query("DELETE FROM ".$prefix."sessions WHERE activitytime<" . $cutoff);
		
	}

	/* 
	*
	* Function: login
	* Args: 	$db	- The database object
	*			$username - The username to login
	*			$password - The password to login
	* Descript:	authenticate a user
	* Returns:	nothing
	*
	*/
	public function login($db, $username, $password){
		
		$prefix = $db->getPrefix();	
		$result = $db->query("SELECT * FROM ".$prefix."users a INNER JOIN ".$prefix."user_groups b ON a.groupid=b.groupid WHERE a.username='" . $db->prep($username) . "' AND a.pass='" . md5($db->prep($password)) . "'");
		if(mysql_num_rows($result) != 1){
			$_SESSION["logged_in"] = "err";
			return "err";
		} else {
			while($row=mysql_fetch_object($result)){
				if($row->verify>0){
					return "activate";
				} else {
					$oldsesid = session_id();
					session_regenerate_id();
					$_SESSION["logged_in"] = true;
					$_SESSION["user"] = $row->username;
					$_SESSION["uid"] = $row->userid;
					$_SESSION["groupid"] = $row->groupid;				
					$_SESSION["console"] = $row->console;
					$_SESSION["rname"] = $row->rname;
					$db->query("UPDATE ".$prefix."sessions SET uid=" . $row->userid . ", sessionid='" . session_id() . "' WHERE sessionid='" . $oldsesid . "'");
				}
			}
			return "ok";
		}
		
	}
	
	/* 
	*
	* Function: logout
	* Args: 	$db	- The database object
	* Descript:	logout a user
	* Returns:	destroyed session
	*
	*/
	public function logout($db){
		
		session_start(); 
		$prefix = $db->getPrefix();	
		$outcome = $db->query("DELETE FROM ".$prefix."sessions WHERE sessionid='" . session_id() . "'");
		if($outcome){
			
			session_unset();
			session_destroy();
			// get a new session
			$this->newsession($db);
		} else {
			$this->updatesession($db);
		}
		
	}
		
	
	/* 
	*
	* Function: auth
	* Args: 	$db	- The database object
	*			$type - The authentication level
	* Descript:	authenticate a protected area
	* Returns:	[boolean] ture if has access, else false
	*
	*/
	public function auth($db, $type){
		$prefix = $db->getPrefix();	
		switch($type){
		
			/* if we are authenticating an admin for the cms*/
			case 1:
				$result = $db->query("SELECT a.mod, a.admin, a.groupid FROM ".$prefix."user_groups a INNER JOIN ".$prefix."users b ON a.groupid=b.groupid WHERE b.userid=" . $_SESSION["uid"]);
				while($row=mysql_fetch_object($result)){
					if($row->admin == 1 && $row->mod == 1 && $row->groupid == $_SESSION["groupid"] ){
						return true;	
					} else {
						return false;	
					}
					
				}
				return false;	
			break;
			
			/* if we are authenticating a mod */
			case 2:
				$result = $db->query("SELECT a.mod, a.groupid FROM ".$prefix."user_groups a INNER JOIN ".$prefix."users b ON a.groupid=b.groupid WHERE b.userid=" . $_SESSION["uid"]);
				while($row=mysql_fetch_object($result)){
					if($row->mod == 1 && $row->groupid == $_SESSION["groupid"] ){
						return true;	
					} else {
						return false;	
					}
					
				}
				return false;	
			break;
						
			/* if we are authenticating the spotlight */
			case 3:
				$result = $db->query("SELECT a.spotlight, a.groupid FROM ".$prefix."user_groups a INNER JOIN ".$prefix."users b ON a.groupid=b.groupid WHERE b.userid=" . $_SESSION["uid"]);
				while($row=mysql_fetch_object($result)){
					if($row->spotlight == 1 && $row->groupid == $_SESSION["groupid"] ){
						return true;	
					} else {
						return false;	
					}
					
				}
				return false;	
			break;
			
			/* if we are authenticating the member's list */
			case 4:
				if(is_numeric($_SESSION["groupid"])){
					$result = $db->query("SELECT memberlist, groupid FROM ".$prefix."user_groups WHERE groupid=" . $_SESSION["groupid"]);
					while($row=mysql_fetch_object($result)){
						if($row->memberlist == 1 && $row->groupid == $_SESSION["groupid"] ){
							return true;	
						} else {
							return false;	
						}
						
					}
				} else {
					return false;	
				}
			break;
			
			default:
				return false;	
			break;
			
		}
		
	}
	
	
	/* 
	*
	* Function: reg
	* Args: 	$db	- The database object
	*			$username - The username
	*			$rname - The real name
	*			$pword - The password
	* Descript:	add a user to the database
	* Returns:	[boolean] ture if has added, else false if username taken already
	*
	*/
	public function reg($db, $config, $username, $username_clean, $rname, $email, $pword){
		$prefix = $db->getPrefix();	
		/* check if the username is taken */
		$result = $db->query("SELECT username FROM ".$prefix."users WHERE username_clean='" . $db->prep($username_clean) . "'");
		if(mysql_num_rows($result)!=0){
			return false;	
		} else {
			$valstr = rand(10000000, 99999999);
			$outcome = $db->query("INSERT INTO ".$prefix."users(username, username_clean, pass, rname, email, groupid, verify) VALUES('" . $db->prep($username) . "', '" . $db->prep($username_clean) . "', '" . md5($db->prep($pword)) . "', '" . $db->prep($rname) . "', '" . $db->prep($email) . "', 2, " . $valstr . ")");
			if($outcome){
				$userid = mysql_insert_id();
				$outcome = $this->sendActivation($db, $config, $userid);
				
				switch($outcome){
					case false:
						return "Mail failed";
					break;
					case "ok":
						return true;
					break;
					case "verified":
						return "verified";
					break;
					case "Mail failed":
						return "Mail failed";
					break;
					default:
						return "Mail failed";
					break;
				}
				
			} else {
				return false;
			}
		}
	}
	
	public function activateResend($db, $config, $username){
		
		$prefix = $db->getPrefix();	
		/* check if the username is taken */
		$result = $db->query("SELECT verify, userid FROM ".$prefix."users WHERE username_clean='" . $db->prep(strtolower($username)) . "'");
		if(mysql_num_rows($result)==0){
			return false;
		} else {
			$outcome = $this->sendActivation($db, $config, mysql_result($result, 0, 'userid'));
			switch($outcome){
				case false:
					return "Mail failed";
				break;
				case "ok":
					return true;
				break;
				case "verified":
					return "verified";
				break;
				case "Mail failed":
					return "Mail failed";
				break;
				default:
					return "Mail failed";
				break;
			}
		}
		
		
	}
	
	public function sendActivation($db, $config, $userid){
	
		$prefix = $db->getPrefix();
		if(is_numeric($userid)){
			$outcome = $db->query("SELECT * FROM ".$prefix."users WHERE userid=".$db->prep($userid));
			if(mysql_num_rows($outcome)==1){
				$userInfo = mysql_fetch_object($outcome);
				if($userInfo->verify>0){
					$board_name = $config->getVal($db, 'board_name');
					$root = $config->getVal($db, 'root');
					$to = $userInfo->email;
					//define the subject of the email
					$subject = $board_name." Activation Email"; 
					//define the message to be sent. Each line should be separated with \n
					$message =  "Hello ".$userInfo->username."!\n\n You have recieved this email after registering an account with us at ".$board_name; 
					$message .= "To acivate this account, please follow this link:\n\n".$root."#val:".$userInfo->userid."-".$userInfo->verify."\n\nThanks,".$board_name;
					//define the headers we want passed. Note that they are separated with \r\n
					//$headers = "From: webmaster@example.com\r\n";
					$mail_sent = @mail( $to, $subject, $message );
					//if the message is sent successfully print "ok". Otherwise print "Mail failed" 
					return $mail_sent ? "ok" : "Mail failed";	
				} else {
					return "verified";	
				}
			} else {
				return false;	
			}
		} else {
			return false;	
		}
	
	}
	
	
	public function validate($db, $userid, $valstr){
		
		if(is_numeric($userid) && is_numeric($valstr)){
			$prefix = $db->getPrefix();
			$result = $db->query("SELECT verify FROM ".$prefix."users WHERE userid=".$db->prep($userid)." AND verify=".$db->prep($valstr));
			if(mysql_num_rows($result) == 1){
				$update = $db->query("UPDATE ".$prefix."users SET verify=0 WHERE userid=".$db->prep($userid));
				if($update){
					return true;
				} else {
					return false;
				}
			} else {
				return false;	
			}
		} else {
			return false;	
		}
		
	}
	
	public function getUser($db, $userid){
		if(is_numeric($userid)){
			$prefix = $db->getPrefix();
			$result = $db->query("SELECT a.*, b.groupname, b.colour, c.* FROM ".$prefix."users a INNER JOIN ".$prefix."user_groups b ON a.groupid=b.groupid INNER JOIN ".$prefix."user_ranks c ON a.rankid=c.rankid WHERE a.userid=".$userid);
			if(mysql_num_rows($result)>0){
				return	$result;
			} else {
				return false;	
			}				
		} else {
			return false;
		}
	}
	
	public function getPostCount($db, $userid){
		if(is_numeric($userid)){	
			$prefix = $db->getPrefix();
			$result = $db->query("SELECT post_id as total FROM ".$prefix."forum_post WHERE user_id=".$userid." AND post_deleted=0");
			if($result){
				return mysql_num_rows($result);
			} else {
				return 0;	
			}
		} else {
			return 0;	
		}
	}
	
	public function getAllUsers($db){
			$prefix = $db->getPrefix();
			$result = $db->query("SELECT a.*, b.groupname, b.colour, c.* FROM ".$prefix."users a INNER JOIN ".$prefix."user_groups b ON a.groupid=b.groupid INNER JOIN ".$prefix."user_ranks c ON a.rankid=c.rankid");
			if(mysql_num_rows($result)>0){
				return	$result;
			} else {
				return false;	
			}				
	}
	
	public function getUserCustomFields($db, $userid){
		if(is_numeric($userid)){
			$prefix = $db->getPrefix();
			$sql = "SELECT * FROM ".$prefix."user_custom_fields_data a INNER JOIN ".$prefix."user_custom_fields b ON a.field_id=b.field_id WHERE a.userid=".$userid." ORDER BY field_order";
			$result = $db->query($sql);
			if(mysql_num_rows($result)>0){
				return	$result;
			} else {
				return false;	
			}				
		} else {
			return false;
		}
	}
	
	public function getAllCustomFields($db){
		$prefix = $db->getPrefix();
		$sql = "SELECT * FROM ".$prefix."user_custom_fields WHERE field_enabled=1 ORDER BY field_order";
		$result = $db->query($sql);
		if(mysql_num_rows($result)>0){
			return	$result;
		} else {
			return false;	
		}				
	}
	
	public function updateCustomFields($db, $userid, $data){
		if(is_numeric($userid)){
			$prefix = $db->getPrefix();
			$fields = explode(';',$data);
			foreach($fields as $field){
				$val = explode(':sp:', $field);
				if(sizeof($val)==2){
					if(is_numeric($val[0])){
						$check = "SELECT field_id FROM ".$prefix."user_custom_fields_data WHERE userid=".$userid." AND field_id=".$val[0];
						$result = $db->query($check);
						if(mysql_num_rows($result)==1){
							$sql = "UPDATE ".$prefix."user_custom_fields_data SET field_data_value='".$db->prep($val[1])."' WHERE userid=".$userid." AND field_id=".$val[0];
							$result = $db->query($sql);								
						} elseif(mysql_num_rows($result)==0){
							$sql = "INSERT INTO ".$prefix."user_custom_fields_data(field_data_value,userid,field_id) VALUES('".$db->prep($val[1])."', ".$userid.", ".$val[0].")";
							$result = $db->query($sql);	
						}
						if(!$result){
							return false;	
						}
					}
				}
			}
			return true;
		} else {
			return false;	
		}
	}
	
	public function buildControl($db, $controlid, $userid){
		if(is_numeric($userid) && is_numeric($controlid)){
			$prefix = $db->getPrefix();
			$sql = "SELECT * FROM ".$prefix."user_custom_fields WHERE field_id=".$controlid." ORDER BY field_order";
			$sql2 = "SELECT * FROM ".$prefix."user_custom_fields_data WHERE userid=".$userid." AND field_id=".$controlid."";
			$fieldResult = $db->query($sql);
			$userFieldResult = $db->query($sql2);
			if($fieldResult){
				
				$field = mysql_fetch_object($fieldResult);	
				$userField = mysql_fetch_object($userFieldResult);	
				switch($field->field_type){
					// inputbox
					case 1:
						$html = "<input name=\"custom_text_pf_%s\" alt=\"%s\" value=\"%s\" class=\"custom_inputbox\" size=\"%s\" />";
						return sprintf($html, $field->field_id, $field->field_id, $userField->field_data_value, $field->field_max_length);
					break;
					
					// textbox
					case 2:
						$html = "<textarea name=\"custom_textbox_pf_%s\" alt=\"%s\" cols=\"\" rows=\"3\" class=\"custom_textbox\">%s</textarea>";
						return sprintf($html, $field->field_id, $field->field_id, $userField->field_data_value);
					break;
					
					// select
					case 3:
						$options = explode(';',$field->field_options);
						$html = sprintf("<select name=\"custom_option_pf_%s\"  class=\"custom_select\">",$field->field_id);
						foreach($options as $option){
							if($option==$userField->field_data_value){
								$html .= sprintf("<option alt=\"%s\" selected=\"selected\">%s</option>",$field->field_id, $option);
							} else {
								$html .= sprintf("<option alt=\"%s\">%s</option>",$field->field_id, $option);
							}
						}
						$html .= "</select>";
						return $html;						
					break;
					
					// radio
					/*
					case 4:
						$options = explode(';',$field->field_options);
						$html = "";
						foreach($options as $option){
							$html .= "<label>";
							if($option==$field->field_data_value){
								$html .= sprintf("<input name=\"custom_radio_pf_%s\" type=\"radio\" value=\"%s\" alt=\"%s\" checked />", $field->field_id, $option, $field->field_id);
							} else {
								$html .= sprintf("<input name=\"custom_radio_pf_%s\" type=\"radio\" value=\"%s\" alt=\"%s\" />", $field->field_id, $option, $field->field_id);
							}
							$html .= sprintf("%s</label>", $option) . "<br />";
						}
						return $html;						
					break;
					*/
					
					// checkbox
					/*
					case 5:
						$options = explode(';',$field->field_options);
						$html = "";
						foreach($options as $option){
							$html .= sprintf("<label>%s", $option);
							if($option==$field->field_data_value){
								$html .= sprintf("<input name=\"custom_checkbox_pf_%s\" type=\"checkbox\" value=\"%s\" alt=\"%s\" checked />", $field->field_id, $option, $field->field_id);
							} else {
								$html .= sprintf("<input name=\"custom_checkbox_pf_%s\" type=\"checkbox\" value=\"%s\" alt=\"%s\" />", $field->field_id, $option, $field->field_id);
							}
							$html .= "</label><br />";
						}
						return $html;	
					break;
					*/
					
				}
			}
		}
	}

	public function getSignature($db, $userid){
		if(is_numeric($userid)){
			$prefix = $db->getPrefix();
			$sql = "SELECT * FROM ".$prefix."user_signature WHERE userid=".$userid;
			$result = $db->query($sql);
			if(mysql_num_rows($result)>0){
				return	$result;
			} else {
				return false;	
			}				
		} else {
			return false;
		}
	}

	public function updateSignature($db, $post, $userid, $sigHtml){
		if(is_numeric($userid)){
			$parsed = $post->parsePost($db, $sigHtml);
			$prefix = $db->getPrefix();
			$sql = "UPDATE ".$prefix."user_signature set sig_tags='".$db->prep($sigHtml)."', sig_html='".$parsed."' WHERE userid=".$userid;
			$result = $db->query($sql);
			if($result){
				return	true;
			} else {
				return false;	
			}				
		} else {
			return false;
		}
	}

	public function newPassword($db, $userid, $oldpw, $newpw){
		if(is_numeric($userid)){
			$prefix = $db->getPrefix();
			$result = $db->query("SELECT * FROM ".$prefix."users WHERE userid=".$db->prep($_SESSION['uid'])." AND pass='".md5($db->prep($oldpw))."'");
			if(mysql_num_rows($result)==1){
				$outcome = $db->query("UPDATE ".$prefix."users SET pass='".md5($db->prep($newpw))."' WHERE userid=".$db->prep($userid));
				if($outcome){
					return true;
				} else {
					return false;	
				}
			} else {
				return false;
			}
		} else {
			return false;	
		}
	}

	public function updateProfile($db, $userid, $fieldArray){
		if(is_numeric($userid) && is_numeric($fieldArray['age'])){
			$prefix = $db->getPrefix();
			$outcome = $db->query("UPDATE ".$prefix."users SET 
							  		email='".$this->escapeField($db->prep($fieldArray['email']))."', 
									rname='".$this->escapeField($db->prep($fieldArray['rname']))."', 
									user_avatar='".$this->escapeField($db->prep($fieldArray['avatar']))."',
									location='".$this->escapeField($db->prep($fieldArray['location']))."',
									age=".$this->escapeField($db->prep($fieldArray['age'])).",
									occupation='".$this->escapeField($db->prep($fieldArray['occupation']))."', 
									interests='".$this->escapeField($db->prep($fieldArray['interests']))."',

									contact_msn='".$this->escapeField($db->prep($fieldArray['contact_msn']))."', 
									contact_icq='".$this->escapeField($db->prep($fieldArray['contact_icq']))."',
									contact_jabber='".$this->escapeField($db->prep($fieldArray['contact_jabber']))."',
									contact_gchat='".$this->escapeField($db->prep($fieldArray['contact_gchat']))."',
									contact_yim='".$this->escapeField($db->prep($fieldArray['contact_yim']))."', 
									contact_website='".$this->escapeField($db->prep($fieldArray['contact_website']))."' 

									WHERE userid=".$db->prep($userid));
			return $outcome;
		} else {
			return false;	
		}

	}
	
	public function escapeField($text){
		
		$text = str_replace('<', '&lt;', $text);
		$text = str_replace('>', '&gt;', $text);
		$text = str_replace('"', "'", $text);
		return $text;
		
	}
	
	public function getOnlineList($db){
		
		$prefix = $db->getPrefix();
		$result = $db->query("SELECT activitytime FROM ".$prefix."sessions");
		if($result){
			return $result;
		} else {
			return false;	
		}
		
	}

	public function getRegisteredOnlineList($db){
		
		$prefix = $db->getPrefix();
		$result = $db->query("SELECT uid, activitytime FROM ".$prefix."sessions WHERE uid>0");
		if($result){
			return $result;
		} else {
			return false;	
		}
		
	}

	public function getGuestOnlineList($db){
		
		$prefix = $db->getPrefix();
		$result = $db->query("SELECT activitytime FROM ".$prefix."sessions WHERE uid=0");
		if($result){
			return $result;
		} else {
			return false;	
		}
		
	}

	public function getVal($db, $field, $user_id){
		
		$prefix = $db->getPrefix();	
		$result = $db->query("SELECT ".$db->prep($field)." FROM ".$prefix."users WHERE userid=".$db->prep($user_id));
		return mysql_result($result, 0, $field);
		
	}
		
}

?>